angular.module('SmartCanteenApp.base', ['ngRoute', 'ngTouch'])

	.config(['$routeProvider', function($routeProvider) {
		$routeProvider.when('/corporation', {
			templateUrl: 'base/corporation.html',
			controller: 'corporationCtrl'
		});
		$routeProvider.when('/canteen', {
			templateUrl: 'base/canteen.html',
			controller: 'canteenCtrl'
		});
		$routeProvider.when('/period', {
			templateUrl: 'base/period.html',
			controller: 'periodCtrl'
		});
		$routeProvider.when('/canteenemp', {
			templateUrl: 'base/canteenemp.html',
			controller: 'canteenCtrl'
		});
		$routeProvider.when('/payment', {
			templateUrl: 'base/payment.html',
			controller: 'canteenCtrl'
		});
		$routeProvider.when('/cost', {
			templateUrl: 'base/cost.html',
			controller: 'canteenCtrl'
		});
		$routeProvider.when('/department', {
			templateUrl: 'base/department.html',
			controller: 'departmentCtrl'
		});
		$routeProvider.when('/users', {
			templateUrl: 'base/users.html',
			controller: 'usersCtrl'
		});
		$routeProvider.when('/stallSetting', {
			templateUrl: 'base/stallSetting.html',
			controller: 'stallSettingCtrl'
		});
		$routeProvider.when('/loginLog', {
			templateUrl: 'base/loginLog.html',
			controller: 'LoginLogCtrl'
		});
	}])

.controller('corporationCtrl', ['$scope', '$timeout', function($scope, $timeout) {
	//企业信息获取 测试
//	var path ="http://192.168.1.114:8080/wisdomeatery/v1/base_system/enterprise"
	var path =$scope.resultPath+"/wisdomeatery/v1/base_system/enterprise"
	var data = {}
	var method = "get"
	$scope.corporation={};
	$scope.isYuemo = false
	$scope.getJson(path,data,method,function(data){
		$scope.corporation = data.data[0]
		console.log($scope.corporation)
		if($scope.corporation.financial_settlement_date==0){
			$scope.isYuemo = true
			$scope.corporation.financial_settlement_date = 0
			console.log($scope.corporation.financial_settlement_date)
		}
	})
	//监听日期变化
	$scope.$watch('corporation.financial_settlement_date', function() {
		if($scope.corporation.financial_settlement_date>28){
			$scope.corporation.financial_settlement_date=28
		}else if($scope.corporation.financial_settlement_date<0){
			$scope.corporation.financial_settlement_date=1
		}
		else if($scope.corporation.financial_settlement_date==0){
			$scope.corporation.financial_settlement_date=null
		}
	});
	$scope.$watch('isYuemo', function() {
			if($scope.isYuemo){
				$scope.corporation.financial_settlement_date=null
			}
		});
	$scope.showCorporation = function() {
			$scope.getJson(path,data,method,function(data){
				$scope.corporation = data.data[0]
				if($scope.corporation.financial_settlement_date ==0){
					$scope.isYuemo = true
				}else{
					$scope.isYuemo = false
				}
			})
			console.log($scope.corporation)
	}
		//保存企业信息
	$scope.saveCorporation = function() {
		if($scope.corporation.name==undefined||$scope.corporation.name==''){
			return
		}
		
		console.log($scope.isYuemo)
		var editpath = path+'/'+$scope.corporation.id
			if($scope.isYuemo){
				$scope.corporation.financial_settlement_date = 0
				console.log($scope.corporation)
			}			
			$scope.getJson(editpath,$scope.corporation,'put',function(data){
				console.log($scope.corporation)
				if(data.code == 0){
					$scope.showSuccess()
					$scope.showCorporation();
				}else{
					$scope.showError(data.msg)
				}
			})
			
		}
	

}])
.controller('departmentCtrl', ['$scope', '$timeout', function($scope, $timeout) {
	$(".modal-dialog").draggable();//为模态对话框添加拖拽
    $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动		
		//获取部门
		var alldeptStatic
		var path =$scope.resultPath+"/wisdomeatery/v1/base_system/departments"
		console.log(path)
		var data = {}
		var method = "get"
		$scope.depts={};
		$scope.sonDepts={};
		$scope.getJson(path,data,method,function(data){
			$scope.depts = data.data
			$scope.sonDepts = data.data
			alldeptStatic = data.data.concat()
		})
	
	$scope.department = function() {
		$scope.getJson(path,data,method,function(data){
			$scope.depts = data.data
			$scope.sonDepts = data.data
			alldeptStatic = data.data.concat()
		})
	}
		//点击表头查询公司下所有部门
	$scope.showAllDept = function() {
			console.log("查询公司下所有部门")
			$scope.getJson(path,data,method,function(data){
				$scope.sonDepts = data.data
			})
		}
		//点击部门根据部门Id查询子部门
	$scope.searchSonDept = function(id) {
			console.log(id);
			//刷新sonDepts对象
		}
		//实时监控组织结构查询 搜索框
	$scope.$watch('searchAccording', function() {
		if($scope.searchAccording == undefined) {
			$scope.searchAccording = '';
		}
		//准备一个空的数组
		var newList = [];
		var arr = alldeptStatic;
		if(arr == undefined)
			return
		
		var length = alldeptStatic.length;

		for(var i = 0; i < length; i++) {
			if(arr[i].name.indexOf($scope.searchAccording) >= 0 || arr[i].code.indexOf($scope.searchAccording) >= 0) {
				newList.push(arr[i]);
			}
		}

		/*     $scope.pagination(newList);*/
		$scope.sonDepts = newList

	});
	//定义组织结构单个对象
	$scope.newdept = [{
		"name": "",
		"code": ""
//		"type": "",
	}];
	$scope.del = function(name,id) {
		$(".delname").html(name);
		$("#deldeptId").html(id);
		$('#delDept').modal('toggle');
	}
	$scope.del_dept = function() {
			var id = $("#deldeptId").html();
			console.log(id)
			var delpath = path+'/'+id
			$scope.getJson(delpath,'','delete',function(data){
				if(data.code == 0){
					$('#delDept').modal('toggle')
					$scope.department(); //刷新页面
					$scope.showSuccess()
				}else{
					$scope.showError(data.msg)
				}
			})
//			angular.forEach(names, function(data) {
//				var delname = $(data).attr("data-name");
//				if(delname == name) {
//					$(data).parent().hide() //执行删除
//					$('#delDept').modal('toggle')
//				}
//			});

		}
		//修改页面跳出
		var editdeptpath
	$scope.edit = function(id) {
		//根据ID发送请求获取某一特定食堂信息
		console.log(id)
		editdeptpath = path+'/'+id
		$scope.getJson(editdeptpath,'','get',function(data){
				$scope.editdept=data.data
		})
		$('#editDept').modal('toggle');
	}

	//修改组织架构确定
	$scope.edit_dept = function() {
			if($scope.editdept[0].code==null||$scope.editdept[0].name==''){
				return
			}
			var emailReg = /^[0-9]*$/;
		    if ( !emailReg.test($scope.editdept[0].code) ) {
		       $scope.showError('组织机构编码只能输入数字')
		       return
		    }
			$scope.getJson(editdeptpath,this.editdept[0],'put',function(data){

				if(data.code == 0){
					$scope.department(); //刷新页面
					$scope.showSuccess()					
				}else{
					$scope.showError(data.msg)
				}
			})
			console.log(this.editdept) //ajax返回this.editdept
			$('#editDept').modal('toggle'); //隐藏模态框
		}
		//新增组织机构
	$scope.saveNewDept = function() {
			if($scope.newdept[0].code==''||$scope.newdept[0].name==''){
				return
			}
			var emailReg = /^[0-9]*$/;
		    if ( !emailReg.test($scope.newdept[0].code) ) {
		       $scope.showError('组织机构编码只能输入正整数')
		       return
		    }
			console.log(this.newdept) //ajax返回this.newdept
			$scope.getJson(path,this.newdept[0],'post',function(data){
				if(data.code == 0){
					$scope.department(); //刷新页面
					$scope.showSuccess()	
					$('#newDept').modal('toggle'); //隐藏模态框
					//清空模态框
					$scope.newdept[0] = {
						"name": "",
						"code": ""
					};					
				}else{
					$scope.showError(data.msg)
					
				}
			})

		}

}])
.controller('canteenCtrl', ['$scope', '$timeout', function($scope, $timeout) {
	$scope.hideCanteen()
	$(".modal-dialog").draggable();//为模态对话框添加拖拽
    $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
		//食堂信息
		$scope.isNewCanteen = false
		//输出目前选中的食堂
		var cUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/canteens' 	
		
		$scope.TempId = ''
		$scope.$on('to-child', function(event,data) {
				 //获取从父控制器传来的当前选中食堂
				$scope.canteenId = data
				console.log($scope.canteenId)
				var forOneCanteen = cUrl+'/'+$scope.canteenId
				$scope.getJson(forOneCanteen,'','get',function(data){
						console.log('获取单个食堂信息')
						$scope.canteenDetails = data.data
			            console.log(data)
			    })
//				$scope.getJson(forOneCanteen+'/payment','','get',function(data){
				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/payments','','get',function(data){
						console.log('获取单个支付')
						$scope.canteenPays = data.data
			            console.log(data)
			    })
				var costUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/costs'
				$scope.getJson(costUrl,'','get',function(data){
						console.log('获取单个食堂信息成本')
			            $scope.costs = data.data[0]    //一个食堂一套
//			            $scope.totalCost = parseFloat($scope.costs.material_fee) + parseFloat($scope.costs.assist_fee) + parseFloat($scope.costs.manage_fee) + parseFloat($scope.costs.energy_fee) + parseFloat($scope.costs.others_fee)
			            console.log(data)
			            //实时成本输入
						$scope.$watch('costs.material_fee+costs.assist_fee+costs.manage_fee+costs.energy_fee+costs.others_fee', function() {
							$scope.totalCost = parseFloat($scope.costs.material_fee) + parseFloat($scope.costs.assist_fee) + parseFloat($scope.costs.manage_fee) + parseFloat($scope.costs.energy_fee) + parseFloat($scope.costs.others_fee)
						});
			    })
				$scope.isNewCanteen = false
//				$scope.showCost()
		});
		$scope.showCanteen = function() {
			$scope.isNewCanteen = false
			var cUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/canteens'
            	$scope.getJson(cUrl,'','get',function(data){
            		
            		$scope.allCanteens = data.data
            		$scope.$emit('all-canteen', $scope.allCanteens);
            	})
            $scope.$on('refresh', function(event,data) {
            	var refreshCanteen = cUrl+'/'+data
				$scope.getJson(refreshCanteen,'','get',function(data){
						$scope.canteenDetails = data.data
			    })
            })
		}
				$scope.firstShowCanteen = function(){
            		var forOneCanteen = $scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId
            		$scope.getJson(forOneCanteen,'','get',function(data){
						console.log('获取单个食堂信息')
			            $scope.canteenDetails = data.data
			            console.log(data)
			            $scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/payments','','get',function(data){
							console.log('获取单个支付')
							$scope.canteenPays = data.data
				            console.log(data)
			   			})
			   		 })
            	}
				$scope.showCEmp = function(){
            		var costUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/employees'
					$scope.getJson(costUrl,'','get',function(data){
							$scope.emps = data.data
				    })
            	}
				$scope.showCost = function(){
            		var costUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/costs'
					$scope.getJson(costUrl,'','get',function(data){
							console.log('获取单个食堂信息成本')
				            $scope.costs = data.data[0]    
				            $scope.totalCost = parseFloat($scope.costs.material_fee) + parseFloat($scope.costs.assist_fee) + parseFloat($scope.costs.manage_fee) + parseFloat($scope.costs.energy_fee) + parseFloat($scope.costs.others_fee)
				            console.log(data)
				            //实时成本输入
							$scope.$watch('costs.material_fee+costs.assist_fee+costs.manage_fee+costs.energy_fee+costs.others_fee', function() {
								console.log($scope.costs.material_fee)
								$scope.totalCost = parseFloat($scope.costs.material_fee) + parseFloat($scope.costs.assist_fee) + parseFloat($scope.costs.manage_fee) + parseFloat($scope.costs.energy_fee) + parseFloat($scope.costs.others_fee)
							});
				    })
            	}
		if( $scope.getCanteenId() != ''){
   				$scope.canteenId =  $scope.getCanteenId() ;
   				//获取某食堂信息
		 		$scope.firstShowCanteen();
		 		//获取食堂下员工
		 		$scope.showCEmp()
		 		//获取成本信息
		 		$scope.showCost()
   		}
		//取消新建食堂
		$scope.cancleNewCanteen = function(){
			$scope.isNewCanteen = false
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId,'','get',function(data){
				$scope.canteenDetails = data.data
			})
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/payments','','get',function(data){
				$scope.canteenPays = data.data
			})
		}
		//新建食堂
		$scope.newCanteen = function(){
			$scope.isNewCanteen = true
			$scope.canteenDetails = [{
				"id": "",
				"name": "",
				"telephone": "",
				"address": "",
				"describe": "",
				"dining_mode": [{
					"id":1,
					"name": "堂食",
					"add_price": 0,
					"is_checked": true
				}, {
					"id":2,
					"name": "自提",
					"add_price": 0,
					"is_checked": false
				}, {
					"id":3,
					"name": "送餐",
					"add_price": 0,
					"is_checked": false
				}, ],
				"exterior_dining": false,
				"field_payment": false
			}]
			$scope.canteenPays = {
				"alipay":false,
				"card":false,
				"no_advance":false,
				"wechat":false
			}
		}
		//保存修改食堂基本信息
		$scope.saveCanteen = function(id) {
			//修改保存
//				var oneCanteenId = $scope.selectOneCanteen
				//判断一下领餐方式是否被选中 至少一个
				console.log($scope.canteenDetails[0])
				var dining = $scope.canteenDetails[0].dining_mode
				var sum = 0
				for(var i = 0;i<dining.length;i++){
					if(!dining[i].is_checked){
						
						sum = sum+1
					}
				}
				if(sum == 3){
					$('#tipText').html('请选择至少一种就餐方式!')
					$('#dining_model').modal('toggle')
					return
				}
				var forOneCanteen = cUrl+'/'+id
				//判断一下支付方式是否被选中 至少一个
				console.log($scope.canteenPays)
				var pays = $('.paytype:checked')
				if(pays.length==0){
					$('#tipText').html('请选择至少一种支付方式!')
					$('#dining_model').modal('toggle')
					return
				}
				//生成支付方式数组
				var payArr = []
				if($scope.canteenPays.alipay == true){
					payArr.push(3)
				}if($scope.canteenPays.card == true){
					payArr.push(4)
				}if($scope.canteenPays.no_advance == true){
					payArr.push(1)
				}if($scope.canteenPays.wechat == true){
					payArr.push(2)
				}
				console.log(payArr)	
				var postData = {
								  "payments": payArr
								}
				if(!$scope.isNewCanteen){
					if($scope.canteenDetails[0].name==''||$scope.canteenDetails[0].telephone==''||$scope.canteenDetails[0].id==''||$scope.canteenDetails[0].address==''||$scope.canteenDetails[0].describe==undefined){
						return
					}
					$scope.getJson(forOneCanteen,$scope.canteenDetails[0],'put',function(data){

					 $scope.sonEditCanteen($scope.canteenDetails[0].id)
						//获取当前食堂信息
//						var oC = cUrl+'/'+$scope.canteenDetails[0].id
//						$scope.getJson(oC,'','get',function(data){
//								console.log('获取单个食堂信息刷新')
//					            $scope.canteenDetails = data.data
//					           
//					    })
						$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenDetails[0].id+'/payments',postData,'put',function(data){
							$scope.showSuccess() //成功提示
						})
					})
					return
				}else{  //新增保存
					if($scope.canteenDetails[0].name==''||$scope.canteenDetails[0].telephone==''||$scope.canteenDetails[0].address==''||$scope.canteenDetails[0].describe==undefined){
						return
					}
//					console.log($scope.allCanteens)
					for (var i=0;i<$scope.allCanteens.length;i++) {
						if($scope.allCanteens[i].name == $scope.canteenDetails[0].name){
							$('#contentHtml').html('食堂已存在！请更改食堂名称后保存！')
							$('#warningChoose').modal('toggle')
							return
						}
					}
//	因压缩注释				delete this.canteenDetails[0].id;
					console.log(this.canteenDetails[0])
					$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens',this.canteenDetails[0],'post',function(data){
						console.log(data)
						var cId = data.data.id
						console.log(cId)//根据ID保存支付方式
						
						$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+cId+'/payments',postData,'put',function(data){
							 $scope.showCanteen() // 刷新页面
			           		 $scope.chooseFirst()
			            	 $scope.showSuccess() //成功提示
						})
			           
				    })
				}
				$scope.$emit('shuaxin', 1);		
		}
		//删除食堂
		$scope.del_canteen = function(id){
			var oneCanteenId = $scope.selectOneCanteen
			var forOneCanteen = cUrl+'/'+id
			$scope.getJson(forOneCanteen,id,'delete',function(data){
				console.log('删除单个食堂信息成功') //在这里请求所有食堂将第一个食堂的id传入方法 父控制器只设置选中？
			    // 重新请求页面内容
				$scope.showCanteen()
				$scope.chooseFirst()
//				$scope.reloadRoute()
				$scope.showSuccess() //成功提示
			
			})
			$scope.$emit('shuaxin', 1);		
			$('#delCanteen').modal('toggle')
		}
		//取消保存
		$scope.cancleCanteenEdit = function(id){
			var forOneCanteen = cUrl+'/'+id
				$scope.getJson(forOneCanteen,'','get',function(data){
						console.log('获取单个食堂信息')
			            $scope.canteenDetails = data.data
			            console.log(data)
			    })
				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+id+'/payments','','get',function(data){
						console.log('获取单个支付')
						$scope.canteenPays = data.data
			            console.log(data)
			    })
		}
		//食堂成本获取
		/* $scope.showCost */
				//保存修改成本
				
		$scope.saveCost = function() {
//			console.log($scope.costs) //返回$scope.costs
//			console.log($scope.TempId)

				$scope.totalCost = parseFloat($scope.costs.material_fee) + parseFloat($scope.costs.assist_fee) + parseFloat($scope.costs.manage_fee) + parseFloat($scope.costs.energy_fee) + parseFloat($scope.costs.others_fee)
				
				console.log($scope.totalCost)
				if($scope.totalCost != 100){
					$('#warningCost').modal('toggle')
					return
				}
				var forOneCanteen = $scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/costs'
				$scope.getJson(forOneCanteen,$scope.costs,'put',function(data){
//						console.log('已修改食堂成本')
						if(data.code == 0){
							$scope.showSuccess('修改成功')
						}else{
							$scope.showError(data.msg)
						}
			    })
		
		}
		//取消编辑成本
		$scope.cancleCost = function(){
			var id  = $('#mainCanteen').val()
			var costUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/costs'
			$scope.getJson(costUrl,'','get',function(data){
				$scope.costs = data.data[0]    
				$scope.totalCost = parseFloat($scope.costs.material_fee) + parseFloat($scope.costs.assist_fee) + parseFloat($scope.costs.manage_fee) + parseFloat($scope.costs.energy_fee) + parseFloat($scope.costs.others_fee)
			})
		}
		$scope.$watch('costs.material_fee+costs.assist_fee+costs.manage_fee+costs.energy_fee+costs.others_fee', function() {
			if($scope.costs == undefined || $scope.costs == 'undefined'){
				return
			}else{
				$scope.totalCost = parseFloat($scope.costs.material_fee) + parseFloat($scope.costs.assist_fee) + parseFloat($scope.costs.manage_fee) + parseFloat($scope.costs.energy_fee) + parseFloat($scope.costs.others_fee)
			}
			
		});

	//食堂员工
		$scope.$on('to-child', function(event,data) {
				 //获取从父控制器传来的当前选中食堂
				$scope.canteenId = data
				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/employees','','get',function(data){
						console.log('获取单个食堂员工')
			            $scope.emps = data.data
			            console.log(data)
			    })
		});
	//维护食堂员工 即增加功能
		//a.显示界面 创建对象 请求部门和职级权限
		$scope.newemp = {    //新增对象
			"username": "",
			"name": "",
			"password": "",
			"confirm_password": "",
			"telephone": "",
			"employee_code": "",
			"address": "",
			"background_login_settings": true,
			"buffet_use_setting": true,
			"type_setting": true,
			"profession": [],
			"organization_id": 0,
			"photo": "",
			"approval_power": ""
		}
		
		$scope.newCemp = function(){
			$('#maintain').modal('toggle')  //显示增加模态框
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/management/get_role','','get',function(data){ //职级权限
				$scope.levels = data.data
				console.log(data.data)
			})
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/departments','','get',function(data){ //部门
				$scope.depts = data.data
			})
		}
		$scope.levelToHtml = function() {
			$scope.afterRoleId = $('input[class*="newlevel"]:checked').attr("data-dataId")
			console.log($scope.afterRoleId)
			$scope.newemp.rolenames = $('input[class*="newlevel"]:checked').val()
			$scope.newemp.role_id = $scope.afterRoleId
			$('#level').modal('toggle')
		}
		//b.回传对象 刷新 $scope.emps
		$scope.submitEmp = function() {
		//	console.log($scope.newemp)
			var levelNames = $('#checkedLevel').val()
			if(levelNames == ''){
				$('#alertLevel').show()
				return
			}else{
				$('#alertLevel').hide()
			}
			if($scope.newemp.confirm_password != $scope.newemp.password){
				$('.psw').addClass('has-error')
			 	$('#alertPsw').show()
				return
			}
			if(this.newemp.organization_id==0){
				$('#alertDept').show()
				return
			}else{
				$('#alertDept').hide()
			}
			//发送请求增加用户
			
			console.log($scope.newemp)
			$scope.getJson('http://192.168.1.118:8080/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/employees',$scope.newemp,'put',function(data){
				console.log(data)
				if(data.code == 0){
					$("#maintain").modal('toggle')
					$scope.getJson('http://192.168.1.118:8080/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/employees','','get',function(data){
						$scope.emps = data.data
					})
				}else{
					$scope.showError(data.msg)
				}
			})
		}
		//隐藏密码不一致提示
		$('.pswinput').on('focus',function(){
	   		$('.psw').removeClass('has-error')
			$('#alertPsw').hide()
	   	})
		//删除员工
		//删除
	$scope.delemp = function(name,id) {
		$(".delempname").html(name);
		$(".delempid").html(id)
		$('#delEmp').modal('toggle');
	}
	$scope.del_emp = function() {
		var id = $(".delempid").html()
		$scope.getJson('http://192.168.1.118:8080/wisdomeatery/v1/base_system/management/users/'+id,'','delete',function(data){
			console.log(data)
			if(data.code == 0){
				$scope.getJson('http://192.168.1.118:8080/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/employees','','get',function(data){
					if(data.code == 0){
						$scope.emps = data.data
						$('#delEmp').modal('toggle');
					}else{
						$scope.showError(data.msg)
					}
				})
			}else{
				$scope.showError(data.msg)
			}
		})
	}
		//支付方式获取
	$scope.payWay = [{
		"in_payment": {
			"no_advance": true,
			"wechat": true,
			"alipay": true,
			"card": true
		},
		"out_payment": {
			"no_advance": false,
			"wechat": true,
			"alipay": true,
			"card": true
		}
	}]
	$scope.showPay = function() {
			this.payWay = [{
				"in_payment": {
					"no_advance": true,
					"wechat": true,
					"alipay": true,
					"card": true
				},
				"out_payment": {
					"no_advance": false,
					"wechat": true,
					"alipay": true,
					"card": true
				}
			}]
		}
		//支付方式修改
	$scope.savePay = function() {
			console.log($scope.payWay)
		}
		//菜品成本获取
//	$scope.costs = {
//		"material_fee": "60",
//		"assist_fee": "15",
//		"manage_fee": "15",
//		"energy_fee": "10",
//		"others_fee": "0"
//	}
//	$scope.showCost = function() {
//			//ajax获取成本信息
//			this.costs = {
//				"material_fee": "60",
//				"assist_fee": "15",
//				"manage_fee": "15",
//				"energy_fee": "10",
//				"others_fee": "0"
//			}
//			console.log($scope.costs)
//		}


}])	
.controller('periodCtrl', ['$scope', '$timeout', function($scope, $timeout) {
	$scope.hideCanteen()
	//分页清空
				$scope.pagination([]);
    			$scope.initial = '10'; //设置默认每页条数
			$(".modal-dialog").draggable();//为模态对话框添加拖拽
		    $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动    			
		//餐别管理
		//餐别管理模块
			$scope.showPeriod = function() {
			//获取餐别信息
			
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/period_times','','get',function(data){
//			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.urlCid+'/period_times','','get',function(data){
				$scope.periods = data.data
				$scope.pagination($scope.periods);
				console.log(data.data)
			})
	}
		if( $scope.getCanteenId() != ''){
		   	$scope.canteenId =  $scope.getCanteenId() ;
		   	//获取基础数据
			$scope.showPeriod();
		}
		$scope.$on('to-child', function(event,data){
			$scope.canteenId = data
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/period_times','','get',function(data){
				console.log(data)
				$scope.periods = data.data
				$scope.dataPL = $scope.periods.length
				$scope.pagination($scope.periods);
			})
		})

//	    $scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/period_times','','get',function(data){
//				$scope.periods = data.data
//				$scope.pagination($scope.periods);
//		})
		//新增餐别
		//定义空对象
	$scope.newPeriod = {
			"name": "",
			"start_time": "10:00",
			"end_time": "18:00",
			"book_start_time": "",
			"book_end_time": "",
			"refund_end_time": "",
			"is_multiple": false,
			"status": 1
	}
		//执行新增餐别
	$scope.saveNewPeriod = function() {
			//验证
			if(this.newPeriod.name==''||this.newPeriod.start_time==''||this.newPeriod.end_time==''
					||this.newPeriod.book_start_time==''||this.newPeriod.book_end_time==''||this.newPeriod.refund_end_time==''||this.newPeriod.template==0){
						return
					}
			var start = this.newPeriod.start_time
			var end = this.newPeriod.end_time
			//验证时间段重叠
			var judge = false;
			angular.forEach($scope.periods, function(data){
				if($scope.newPeriod.start_time <data.end_time && $scope.newPeriod.end_time>data.start_time){
					judge = true;
					return false
				}
			});
			if( judge ){
				$scope.showError('时间段不能重叠')
				return;
			}
			//end 时间段重叠
			//起始时间验证
			if(start > end || start == end) {
				$("#warningTime").modal('toggle')
				return
			} else {
				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/period_times',this.newPeriod,'post',function(data){
					console.log(data)
					if(data.code == 0){
						$scope.newPeriod = {} //清空对象
						$scope.showPeriod() //重新请求餐别列表
						$scope.showSuccess()
					}else{
						$scope.showError(data.msg)
					}
				})

				$("#newPeriod").modal('toggle') //隐藏模态框
			}
		}
		//删除餐别
	$scope.showperiod_del = function(id) {
		//根据ID删除餐别
		$("#periodId").val(id)
		$("#delPeriods").modal('toggle')
	}
	$scope.del_periods = function() {
			var delId = $("#periodId").val() //回传delId 根据ID删除餐别
			$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/period_times/'+delId,'','delete',function(data){
				if(data.code == 0){
					$scope.showSuccess()
					$scope.showPeriod()  //重新请求列表内数据
				}else{
						$scope.showError(data.msg)
				}
			})
			$("#delPeriods").modal('toggle') //隐藏删除模态框
	}
		//停用启用餐别
	$scope.togglePeriod = function(id, status) {
		console.log(status)
			if(status == true) { //根据Id启用餐别
				console.log("根据Id启用餐别")
				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/period_times/'+id+'/enable','','put',function(data){
					if(data.code == 0){
						$scope.showSuccess()
						$scope.showPeriod()  //重新请求列表内数据
					}
				})
			} else if(status == false) {
				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/period_times/'+id+'/disenable','','put',function(data){
					if(data.code == 0){
						$scope.showSuccess()
						$scope.showPeriod()  //重新请求列表内数据
					}
				})
			}
		}
		//修改&查看餐别详情
	$scope.editPeriod = function(id) {
		$scope.thisPeriodId = id
		$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/period_times/'+id,'','get',function(data){
			console.log(data)

				$scope.period = data.data

		})
			$('#detail_Periods').modal('toggle')
		}
		//提交修改
	$scope.savePeriod = function() {
		//验证
		if($scope.period.name==undefined||$scope.period.start_time==undefined||$scope.period.end_time==undefined
					||$scope.period.book_start_time==undefined||$scope.period.book_end_time==undefined||$scope.period.refund_end_time==undefined){
						return
		}
			console.log($scope.period) //回传对象
			//验证时间重叠
			var judge = false;
			angular.forEach($scope.periods, function(data){
				if($scope.period.id != data.id){
					if($scope.period.start_time <data.end_time && $scope.period.end_time>data.start_time){
						judge = true;
						return false
					}					
				}
			});
			if( judge ){
				$scope.showError('时间段不能重叠')
				return;
			}
			//end时间重叠验证
			//起始时间验证
			if($scope.period.start_time > $scope.period.end_time || $scope.period.start_time == $scope.period.end_time) {
				$("#warningTime").modal('toggle')
				return
			}else{
				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'+$scope.canteenId+'/period_times/'+$scope.thisPeriodId,$scope.period,'put',function(data){
					$('#detail_Periods').modal('toggle')
					if(data.code == 0){
						$scope.showPeriod() //刷新					
					}else{
						$scope.showError(data.msg)
					}
				})
				console.log($scope.period)
			}
		}

}])	
.controller('usersCtrl', ['$scope', '$timeout', function($scope, $timeout) {
	$(".modal-dialog").draggable();//为模态对话框添加拖拽
    $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
//用户管理页面
				if( $scope.getCanteenId() != ''){
		   				$scope.canteenId =  $scope.getCanteenId() ;
		   		}
				$scope.$on('to-child', function(event,data) {
					//获取从父控制器传来的当前选中食堂
					$scope.canteenId = data;
				});
//阻止冒泡
$scope.stopPop = function(e){
	e.stopPropagation()
}
//实时监控用户查询 搜索框
$scope.staticUsers = []
	$scope.$watch('searchUserAccording', function() {
		if($scope.searchUserAccording == undefined) {
			$scope.searchUserAccording = '';
		}
		//准备一个空的数组
		
		var newList = [];
		var arr = $scope.staticUsers;
		var length = arr.length;
		
		for(var i = 0; i < length; i++) {
			if(arr[i].name.indexOf($scope.searchUserAccording) >= 0 || arr[i].username.indexOf($scope.searchUserAccording) >= 0|| arr[i].telephone.indexOf($scope.searchUserAccording) >= 0) {
				newList.push(arr[i]);
			}
		}

		$scope.pagination(newList);

	});
//请求部门信息
    
		var deptUrl = $scope.resultPath+"/wisdomeatery/v1/base_system/departments"
		$scope.getJson(deptUrl,'','get',function(data){
			$scope.depts = data.data
//			console.log('部门:',data)
	    })

//分页清空
    			$scope.pagination([]);
    			$scope.initial = '10'; //设置默认每页条数
		//左侧根据部门查询部门下员工
	$scope.searchByDept = function(id) {
			var searchUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/management/users?department_id='+id
			$scope.getJson(searchUrl,'','get',function(data){
				console.log(data.data)
				$scope.pagination(data.data);
			})
		}
		//首次进入用户管理界面 
	$scope.first_div = true; //显示请选择用户
	//请求所有用户
	var userUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/management/users'
	$scope.getJson(userUrl,'','get',function(data){
			$scope.corporationemps = data.data
			$scope.pagination($scope.corporationemps);
			console.log(data)
			$scope.staticUsers = data.data.concat()
	})
	$scope.showAllEmp = function(){
		$scope.getJson(userUrl,'','get',function(data){
			$scope.corporationemps = data.data
			console.log('refresh'+$scope.corporationemps)
			$scope.pagination($scope.corporationemps);
			$scope.staticUsers = data.data.concat()
		})
	}
	
		//实时监控维护员工查询 搜索框

	//点击行时触发 查看详情
	//初次进入页面隐藏详情
	$scope.details = [];
	$scope.showdetail = function(eid) {
		
		$scope.first_div = false //显示详情
		$scope.newUser_div = false //隐藏新建用户
		$scope.detail_div = true //隐藏提示选择用户
		$scope.edit_div = false
		/* alert(id) */ //发送请求 根据ID查询该员工信息
		var userUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/management/users/'+eid
		$scope.getJson(userUrl,'','get',function(data){
				$scope.details = data.data
				console.log(data.data)
		})
	}
	//发卡按钮
	$scope.send = function(phone, event, name) {
			event.stopPropagation();
			/* alert("准备发卡，发卡ID"+id); */
			$scope.sendCardName = name
			$scope.sendCardPhone = phone
			$("#sendOneCard").modal('toggle')
		}
		//定义newCard对象
	$scope.newCard = {
			"terminalNo": "",
			"operaterName": "",
			"cardType": "",
			"cardNo": "",
			"userName": "",
			"phoneNumber": "",
			"initialAmount": "",
			"deposit": "",
			"expense": "",
			"moneyDistribution": "",
			"paymentType": "",
			"paymentPassword": "",
			"validDate": ""
		}
		//执行发卡 向后台传newCard对象
	$scope.sendCard = function() {
			$scope.newCard.userName = this.sendCardName
			$scope.newCard.phoneNumber = this.sendCardPhone
			console.log(this.newCard)
		}
		//退卡按钮
	$scope.tui = function(id, event) {
			event.stopPropagation();
			alert("准备退卡，退卡ID" + id);
		}
		//判断是否已发卡
	$scope.showorhide = function(flag) {
			if(flag == 'true') {
				return true;
			} else {
				return false;
			}
	}
		//权限级别获取
	var levelUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/management/get_role'
	$scope.getJson(levelUrl,{},'get',function(data){
			$scope.levels = data.data
	})
		//显示选择权限蒙版
	$scope.showlevel = function() {
			$('#level').modal('toggle')
	}
			//声明一个User对象用于新建
	$scope.onenewUser = {
		"username": "",
		"name": "",
		"password": "",
		"telephone": "",
		"background_login_settings": false,
		"organization_id": 0,
		"role_id": "",
		"internal_user": true
	} 
	//用户名长度监听
	$scope.$watch('onenewUser.username + details[0].username', function() {
		if($scope.onenewUser.username>99999999){
			$scope.showError('用户名不能超过8位！请重新输入')
			$scope.onenewUser.username = parseInt($scope.onenewUser.username/10)
		}
		if( !isNumber($scope.onenewUser.username+'')){
			$scope.onenewUser.username = parseInt(($scope.onenewUser.username+'').substring(-1))
		}
		if($scope.details[0] != undefined){
			if($scope.details[0].username>99999999){
				$scope.showError('用户名不能超过8位！请重新输入')
				$scope.details[0].username = parseInt($scope.details[0].username/10)
			}
			if( !isNumber($scope.details[0].username+'')){
				$scope.details[0].username = parseInt(($scope.details[0].username+'').substring(-1))
			}
		}

	});
		//获取已选权限
	$scope.levelToHtml = function() {
//			if($scope.details != undefined){
//				$scope.details[0].profession = $scope.levels
//			}
			$scope.afterRoleId = $('input[class*="newlevel"]:checked').attr("data-dataId")
			console.log($scope.afterRoleId)
			$scope.onenewUser.rolenames = $('input[class*="newlevel"]:checked').val()
			$scope.onenewUser.role_id = $scope.afterRoleId
			$('#level').modal('toggle')
	}
	$scope.editlevelToHtml = function() {
		$scope.afterRoleId = $('input[class*="editlevel"]:checked').attr("data-dataId")
		$scope.details[0].role_id = $scope.afterRoleId
		$scope.details[0].role_name = $('input[class*="editlevel"]:checked').val()
		$('#editLevel').modal('toggle')
	}
		//详情显示与添加用户切换
	$scope.first_div = true
	$scope.newUser = function() {
			$scope.first_div = false //隐藏提示选择用户
			$scope.detail_div = false
			$scope.newUser_div = true
			$scope.edit_div = false
			$scope.isTel = true
		}
		//取消添加
	$scope.cancel = function() {
			$scope.newUser_div = false;
			$scope.detail_div = false;
			$scope.first_div = true;
			$scope.edit_div = false
	}

		//保存添加用户

	$scope.saveNewUser = function() {
			//验证
			console.log(this.onenewUser)

			//1.1 验证基本属性
			if(this.onenewUser.name == '' || this.onenewUser.organization_id==0){
				$("#newAlert").modal('toggle')
					return
			}
			//1.2 登录后台时验证用户名密码
			if(this.onenewUser.background_login_settings){
				if(this.onenewUser.username=='' || this.onenewUser.password==''||this.onenewUser.role_id == ''){
					$("#newAlert").modal('toggle')
					return
				}
				//1.2.1密码纯数字验证
				if(!isInteger($scope.onenewUser.password)){
					$scope.showError('密码应为纯数字！')
					return
				}
				//1.2.2用户名纯数字验证
				if(!isInteger($scope.onenewUser.username)){
					$scope.showError('用户名应为纯数字！')
					return
				}
			}
			//1.3 验证手机号
			if($scope.onenewUser.telephone != ''){
				$scope.isTel = checkMobile($scope.onenewUser.telephone)
			}
			if(!$scope.isTel){
				$scope.showError('请填写正确手机号')
				return
			}
			
			//执行新增
			$scope.getJson(userUrl+'/'+$scope.canteenId,this.onenewUser,'post',function(data){
					console.log(data)
					if(data.code == 0){
						$scope.onenewUser = {} //清空容器
						$scope.showAllEmp() 	//重新请求所有员工列表 corporationemps
						$scope.showSuccess() //成功提示
						$scope.first_div = true
						$scope.detail_div = false
						$scope.newUser_div = false
						$scope.edit_div = false
					}else{
						$scope.showError(data.msg)
					}
			})


		}
		//启用/停用用户 模板模式
	$scope.userStatus = true //用户启用中
		//启用
	$scope.applyUser = function() {
		var code = $("#editFlag").attr("data-code")
						console.log(code)
		$("#showToggle").html("确定要启用该员工吗?")
		$("#hideCode").html(code)
		$("#stopOrOpen").modal('toggle')
	}
	$scope.stopUser = function() {
			var code = $("#editFlag").attr("data-code")
				/*  alert("要停用的员工编号是"+code)
				 $scope.userStatus = true */
				console.log(code)
			$("#showToggle").html("确定要停用该员工吗?")
			$("#hideCode").html(code)
			$("#stopOrOpen").modal('toggle')
}
		//点击蒙版中确认按钮 触发改变用户状态事件
	$scope.setStatus = function() {

			var code = $("#hideCode").html(); //获取要改变状态的用户编码
			$("#stopOrOpen").modal('toggle')
				/* alert("要停用或启用的员工编码是"+code) */
			if($scope.userStatus == true) {
				$scope.userStatus = false;
			} else {
				$scope.userStatus = true
			}
		}
	//启用/停用用户 点击一次模式
	$scope.toggleUser = function(toggleId,status){
		if(status == true){
			$scope.getJson( $scope.resultPath+'/wisdomeatery/v1/base_system/management/users/'+toggleId+'/disenable','','put',function(data){
				if(data.code == 0){
					$scope.showSuccess()
					$scope.details[0].is_enabled = false
				}else{
					$scope.showError(data.msg)
				}
	
			})
		}else{
			$scope.getJson( $scope.resultPath+'/wisdomeatery/v1/base_system/management/users/'+toggleId+'/enable','','put',function(data){
				if(data.code == 0){
					$scope.showSuccess()
					$scope.details[0].is_enabled = true
				}else{
					$scope.showError(data.msg)
				}
			})
		}
	}
		//编辑用户页面调出
	$scope.editUser = function(empcode) {
//			$scope.levelNames=[]
//			//取出权限名称
//			for(var i = 0;i<$scope.details[0].profession.length;i++){
//				var name = $scope.details[0].profession[i].name
//				$scope.levelNames.push(name)
//			}
			console.log($scope.details[0])
			$scope.first_div = false
			$scope.detail_div = false
			$scope.newUser_div = false
			$scope.edit_div = true
	}
	$scope.editlevels = function(){
//		$('input[class*="editlevel"]').val($scope.details[0].role_name) 
		//判断用户现有权限与所有权限表中的重叠 如果有更改所有权限表中checked属性
//		for(var i = 0;i<$scope.levels.length;i++){
//			$scope.levels[i].is_checked = false
//			for(var j = 0;j<$scope.details[0].profession.length;j++){
//				if($scope.levels[i].name == $scope.details[0].profession[j].name && $scope.details[0].profession[j].is_checked== true){
//					$scope.levels[i].is_checked = true
//				}
//			}
//		}
		$('#editLevel').modal('toggle')
	}
		//编辑用户中用户更改部门模态框弹出
//	$scope.userCheckDept = function() {
//			$("#deptForUser").modal('toggle')
//		}
		//模态框中选中部门
//	$scope.sureDept = function(e) {
//			$(e.target).parent().addClass('selected') //为选中项添加高亮
//			$(e.target).parent().siblings().removeClass('selected') //去除其他项的高亮形式
//		}
		//点击确定获取选中部门 并赋值 details[0].organization
//	$scope.saveUserDept = function() {
//			var deptname = $("li[class*='selected']").children().text();
//			$scope.details[0].organization = deptname
//			console.log($scope.details[0].organization)
//			$("#deptForUser").modal('toggle')
//		}
		//编辑用户保存
	$scope.saveUserEdit = function(id){
		var userEditUrl = $scope.resultPath+'/wisdomeatery/v1/base_system/management/users/'+id
		console.log($scope.details[0])
		//验证
		//1.1姓名不为空
		if($scope.details[0].name==undefined){
			$scope.showError('请填写姓名')
			return
		}
		//1.2 当为后台登录用户时 用户名 密码 确认密码 职级权限不为空
		if($scope.details[0].background_login_settings){
			if($scope.details[0].username == '' || $scope.details[0].username == undefined || $scope.details[0].password == '' 
				|| $scope.details[0].password == undefined || $scope.details[0].role_id==null){
				$scope.showError('请检查信息完整度')
				return
			}
			//1.3密码纯数字验证
			
			if(!isInteger($scope.details[0].password)){
				$scope.showError('密码应为纯数字！')
				return
			}
			//1.2.2用户名纯数字验证
				if(!isInteger($scope.details[0].username)){
					$scope.showError('用户名应为纯数字！')
					return
				}
			//1.4验证角色
			if($scope.details[0].role_id == undefined){
				$scope.showError('请填写用户角色权限')
				return
			}
			
			//1.2.1 验证密码一致性
//			if($scope.details[0].password != $scope.details[0].confirm_password){
//				$('.editpsw').addClass('has-error')
//				return
//			}else{
//				$('.editpsw').removeClass('has-error')
//			}
	}
			//1.3 验证手机号
			if($scope.details[0].telephone != '' || $scope.details[0].telephone == undefined){
				$scope.isTel = checkMobile($scope.details[0].telephone)
			}
			if(!$scope.isTel){
				$scope.showError('请填写正确手机号')
				return
			}
				
		console.log($scope.details[0])
		$scope.getJson(userEditUrl,$scope.details[0],'put',function(data){
				if(data.code == 0){
					$scope.first_div = true //显示详情
					$scope.newUser_div = false //隐藏新建用户
					$scope.detail_div = false //隐藏提示选择用户
					$scope.edit_div = false
					$scope.showSuccess() //成功提示
					$scope.showAllEmp()					
				}else{
					$scope.showError(data.msg)
				}
		})
	}
		//取消编辑用户
	$scope.cancleUserEdit = function() {
			$scope.first_div = true 
			$scope.newUser_div = false 
			$scope.detail_div = false 
			$scope.edit_div = false
		}
		//删除用户
	$scope.deleteUserId = "",
		$scope.showDeleteUser = function(id) {
			console.log(id)
			if(id != null){
				this.deleteUserId = id
				$("#deleteUser").modal('toggle')	
			}
		}
	$scope.deleteUser = function() {
		$scope.getJson(userUrl+'/'+this.deleteUserId,'','delete',function(data){
			if(data.code == 0){
				$("#deleteUser").modal('toggle')
				//刷新右侧
				$scope.first_div = true
				$scope.detail_div = false
				$scope.newUser_div = false
				$scope.edit_div = false
				$scope.showAllEmp(); //重新请求用户
				$scope.showSuccess() //成功提示
			}else{
				$scope.showError(data.msg)
			}
		})
		console.log(this.deleteUserId);
		
			
	
	}

}])	
.controller('stallSettingCtrl', ['$scope', '$timeout', function($scope, $timeout) {
				$scope.pagination([]);
				$scope.hideCanteen()
				$(".select2").select2();
            	$(".modal-dialog").draggable();//为模态对话框添加拖拽
        		$(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
//分页清空		
				//var basePath = 'http://192.168.1.114:8080/wisdomeatery/v1/base_system/canteens/'
				var basePath = $scope.resultPath+'/wisdomeatery/v1/base_system/canteens/'
    			
    			$scope.initial = '10'; //设置默认每页条数
//请求所有用户用于新建模板
				$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/management/users','','get',function(data){
					$scope.managers = data.data
					console.log($scope.managers)
				})
//自动填入主管电话
				$scope.getPhone = function(id,str){
					console.log($scope.managers)
					
					for (var i = 0;i<$scope.managers.length;i++) {
						if($scope.managers[i].id == id){
							if(str == 'edit'){
								$scope.win.manager_phone = $scope.managers[i].telephone
							}else{
								$scope.newWindow.manager_phone = $scope.managers[i].telephone
							}
						}
					}
				}
				
//档口设置
//获取当前食堂
		//获取基础数据
	    $scope.showWindows = function(){
	    	//请求档口
			var dangkoupath = basePath+$scope.canteenId+'/windows'
			$scope.getJson(dangkoupath,'','get',function(getdatas){
				$scope.windows = getdatas.data
				$scope.pagination($scope.windows); //分页
			})
	    }
	   
   		if( $scope.getCanteenId() != ''){
   				$scope.canteenId =  $scope.getCanteenId() ;
   				$scope.pagination([]);
   				//获取基础数据
		 		$scope.showWindows();
   		}
		$scope.$on('to-child', function(event,data) {
			//获取从父控制器传来的当前选中食堂
			$scope.canteenId = data;
			$scope.showWindows();
		});
		$scope.windows=[]
		
		//删除档口
		//要修改、删除的档口id标识符
		$scope.WindowId = null
	$scope.showwin_del = function(id) {
		$scope.WindowId = id
		$("#delWindows").modal('toggle')
	}
	$scope.del_windows = function() {
			console.log($scope.WindowId) //要删除的档口id
			var wPath = basePath+$scope.canteenId+'/windows/'+$scope.WindowId
			$scope.getJson(wPath,'','delete',function(data){
					console.log(data)
				if(data.code == 0){
					$scope.showWindows() // 重新请求数据
					$scope.showSuccess() //成功提示
				}else{
					$scope.showError(data.msg)
				}
			})
			$("#delWindows").modal('toggle') //隐藏删除模态框
				//重新请求列表内数据
		}
		//停用档口
	$scope.showwin_stop = function(id,flag) {
		var wPath = basePath+$scope.canteenId+'/windows/'+id
			if(flag=='stop'){ //停用档口
				$scope.getJson(wPath+'/stop','','put',function(data){
					console.log(data)
					if(data.code == 0){
						$scope.showWindows()
						$scope.showSuccess()
					}else{
						$scope.showError(data.msg)
					}
				})
			}else if(flag=='open'){ //启用档口
				$scope.getJson(wPath+'/start','','put',function(data){
					if(data.code == 0){
						$scope.showWindows()
						$scope.showSuccess()
					}else{
						$scope.showError(data.msg)
					}
				})
			}
				
	}
	$scope.stop_windows = function() { //模态框方法 未用
			var delId = [];
			//获取选中档口id
			var windows = $("input[name*='checkwindows']:checked")
			angular.forEach(windows, function(data) {
				var id = $(data).attr("id")
				delId.push(id)
			});
			console.log(delId) //数组delId为要删除的门店id数组
			$("#stopWindows").modal('toggle') //隐藏删除模态框
				//重新请求列表内数据
			$scope.showWindows()
	}
		//新建档口
		//创建档口对象
	$scope.newWindow = {
		"name": "",
		"manager_id": "0",
		"manager_phone": ""
	}
	$scope.saveNewWindow = function() {
		//验证
		if($scope.newWindow.name==''||$scope.newWindow.manager_id=='0'||$scope.newWindow.manager_phone==''){
			return
		}
		//执行新增
		var nWPath = basePath+$scope.canteenId+'/window'
		$scope.getJson(nWPath,this.newWindow,'post',function(data){
			if(data.code == 0){
					$scope.showWindows() // 重新请求数据
					$scope.showSuccess() //成功提示
					$scope.newWindow = {
						"name": "",
						"manager_id": "",
						"manager_phone": ""
					}
					$("#newWindow").modal('toggle')
			}else{
				$scope.showError(data.msg)
			}
		})
			
		console.log(this.newWindow)
			
		}
	$scope.staticWindowItems = []
		//获取档口内产品
	$scope.showItems = function(windowId) {
			var iPath = basePath+$scope.canteenId+'/windows/'+windowId+'/items'
			$scope.getJson(iPath,'','get',function(data){
					$scope.windowItems = data.data
					$scope.staticWindowItems = $scope.windowItems.concat()
			})
			$("#items").modal('toggle')
			

//			$scope.windowItems = [{
//				"id": 1,
//				"name": "红烧肉",
//				"unit": "份",
//				"in_price": 7,
//				"out_price": 8,
//				"chief_id": 008,
//				"chief_name": "刘一帆",
//				"status": true
//			}, {
//				"id": 2,
//				"name": "炖芸豆",
//				"unit": "份",
//				"in_price": 6,
//				"out_price": 7,
//				"chief_id": 008,
//				"chief_name": "刘一帆",
//				"status": true
//			}]
			
			
		}
		//修改档口
	$scope.showwin_edit = function(wid) {
			console.log(wid) //根据ID请求档口信息 赋值给win
			$scope.editId = wid
			var wPath = basePath+$scope.canteenId+'/windows/'+$scope.editId
			$scope.getJson(wPath,'','get',function(data){
					console.log(data)
					$scope.win = data.data
			})
			$("#editWindow").modal('toggle')
		}
		//保存修改档口
	$scope.saveWindow = function() {
		console.log($scope.win) //返回this.win 为修改后对象
		var wPath = basePath+$scope.canteenId+'/windows/'+$scope.editId
			$scope.getJson(wPath,$scope.win,'put',function(data){
				if(data.code == 0){
					$scope.showWindows(); //重新请求档口数据
					$scope.showSuccess() //成功提示	
					$("#editWindow").modal('toggle')
				}
				else{
					$scope.showError(data.msg)
				}
			})
		
	
	}
	    //实时监控组织结构查询 搜索框
		$scope.$watch('searchItemInWindow', function() {
			if($scope.searchItemInWindow == undefined) {
				$scope.searchItemInWindow = '';
			}
			//准备一个空的数组
			var newList = [];
			var arr = $scope.staticWindowItems;
			var length =arr.length;
			
			for(var i = 0; i < length; i++) {
				if(arr[i].name.indexOf($scope.searchItemInWindow) >= 0 ) {
					newList.push(arr[i]);
				}
			}
	
			/*     $scope.pagination(newList);*/
			$scope.windowItems = newList

		});
		$('#datepicker').val($scope.getNowFormatDate());
		//日历选择
		$('#datepicker').datepicker({
		  autoclose: true
		});
		//打开获取档口成本选择日期模板
		$scope.openToggle = function(){
			$('#getWindowCost').modal('toggle');
		}
		//关闭
		$scope.hideWindowCost = function(){
			$('#getWindowCost').modal('toggle');
		}
		//获取指定日期档口成本
		$scope.getWindowCost = function(selectData){
				$scope.getJson($scope.resultPath+"/wisdomeatery/v1/canteens/"+$scope.canteenId+"/calcWindowCost/"+selectData,"","POST",function(data){
					console.log(data);
					if(data.code == 0){
						$scope.showSuccess(data.msg) 
					}else{
						$scope.showError(data.msg)
					}
				})
			}
		//关闭的同时去获取成本
		$scope.saveWindowCost = function(){
			//判断是否选择了日期
			console.log($('#datepicker').val());
			if( $('#datepicker').val() == '' || $('#datepicker').val() == undefined || $('#datepicker').val() == null){
				$scope.showError('请选择日期');
				return;
			}
			
			$scope.getWindowCost($('#datepicker').val());
			$('#getWindowCost').modal('toggle');
		}
		
		

}])	
.controller('LoginLogCtrl',['$scope','$timeout',function($scope,$timeout){
	$(".modal-dialog").draggable();//为模态对话框添加拖拽
    $(".modal").css("overflow", "hidden");//禁止模态对话框的半透明背景滚动
	//分页
	$scope.initial = '10'; //设置默认每页条数
	$scope.pagination([]); //清空容器
	//日期选择
	$('#reservation').daterangepicker();
	//获取当前日期
	$scope.getNowFormatDate = function() {
				    var date = new Date();
				    var seperator1 = "-";
				    var seperator2 = ":";
				    var month = date.getMonth() + 1;
				    var strDate = date.getDate();
				    if (month >= 1 && month <= 9) {
				        month = "0" + month;
				    }
				    if (strDate >= 0 && strDate <= 9) {
				        strDate = "0" + strDate;
				    }
				    var now = date.getFullYear() + seperator1 + month + seperator1 + strDate;
				    
				    return now;
				}
	//获取登录日志
	$scope.getJson($scope.resultPath+'/wisdomeatery/v1/base_system/login_log?start_time='+$scope.getNowFormatDate()+'&end_time='+$scope.getNowFormatDate(),'','get',function(data){
		console.log(data)
		$scope.logs = data.data
		$scope.logsL = $scope.logs.length
		for(var i = 0; i < $scope.logsL; i++) {
			if($scope.logs[i].department_name == null){
				$scope.logs[i].department_name = '无'
			}
			
		}
		$scope.staticLogs = $scope.logs.concat();
		$scope.pagination($scope.logs); //传入数据
	})
	//查询条件
	$scope.searchLogBy = {
		"corporation_name": "",
		"start_time": "",
		"end_time": "",
		"department_name": "",
	}
	$scope.LoginDate = $scope.getNowFormatDate()+' '+'至'+' '+$scope.getNowFormatDate()
	
    //发送请求根据条件查询
    $scope.searchLog = function(){
    	var arr = $scope.LoginDate.split('至');
	    $scope.searchLogBy.start_time = $.trim(arr[0])
	    $scope.searchLogBy.end_time = $.trim(arr[1])
    	console.log(this.searchLogBy)
    	var getUrl1 = $scope.resultPath+'/wisdomeatery/v1/base_system/login_log?enterprise_name='+$scope.searchLogBy.corporation_name+'&start_time='+$scope.searchLogBy.start_time
    	var getUrl2 = '&end_time='+$scope.searchLogBy.end_time+'&department_name='+$scope.searchLogBy.department_name
    	var getUrl = getUrl1+getUrl2
    	$scope.getJson(getUrl,'','get',function(data){
			console.log(data)
			$scope.logs = data.data
			$scope.logsL = $scope.logs.length
			$scope.staticLogs = $scope.logs.concat();
			$scope.pagination($scope.logs); //传入数据
		})
    }
}])
